<template>
  <view class="index">
    <view>
      <view class="header">
        <text class="title">ROI计算器</text>
      </view>
      <view class="ind_from">
        <view class="section-title">基础信息</view>
        <view class="form-grid">
          <view class="form-item">
            <view class="label">成本:</view>
            <view class="input-unit-group">
              <input
                class="input"
                v-model="formData.cost"
                type="digit"
                placeholder="请输入成本"
                @input="validateCost"
                @blur="formatCost"
              />
              <view class="unit blue">元</view>
            </view>
          </view>
          <view class="form-item">
            <view class="label">售价:</view>
            <view class="input-unit-group">
              <input
                class="input"
                v-model="formData.price"
                type="digit"
                placeholder="请输入售价"
                @input="validatePrice"
                @blur="formatPrice"
              />
              <view class="unit blue">元</view>
            </view>
          </view>
          <view class="form-item">
            <view class="label">退货率:</view>
            <view class="input-unit-group">
              <input
                class="input"
                v-model="formData.returnRate"
                type="digit"
                placeholder="0-100"
                @input="validateReturnRate"
                @blur="formatReturnRate"
              />
              <view class="unit blue">%</view>
            </view>
          </view>
          <view class="form-item">
            <view class="label">平台服务费率:</view>
            <view class="input-unit-group">
              <input
                class="input"
                v-model="formData.serviceFeeRate"
                type="digit"
                placeholder="0-100"
                @input="validateServiceFeeRate"
                @blur="formatServiceFeeRate"
              />
              <view class="unit blue">%</view>
            </view>
          </view>
        </view>
      </view>

      <view class="btn" @click="submit">
        <text class="btn-text">{{ isUnlock ? "计算" : "看广告获取计算结果" }}</text>
      </view>
      <view class="pub_ad_banner">
        <!-- #ifdef MP-TOUTIAO -->
        <ad
          :unit-id="adBannerIdDouyin"
          :ad-intervals="30"
          :fixed="false"
          type="banner"
          scale="100"
        />
        <!-- #endif -->
        <!-- #ifdef MP-KUAISHOU -->
        <ad :type="100011054" :unit-id="adBannerIdKuaishou"></ad>
        <!-- #endif -->
      </view>

      <view class="ind_from result">
        <view class="section-title">计算结果</view>
        <view class="row">
          <view class="label">预估利润</view>
          <view class="value" :class="{'positive': result.estimatedProfit > 0, 'negative': result.estimatedProfit < 0}">
            {{ showResult ? result.estimatedProfit + '元' : '--' }}
          </view>
        </view>
        <view class="row">
          <view class="label">结算利润</view>
          <view class="value" :class="{'positive': result.settlementProfit > 0, 'negative': result.settlementProfit < 0}">
            {{ showResult ? result.settlementProfit + '元' : '--' }}
          </view>
        </view>
        <view class="row">
          <view class="label">毛利润率</view>
          <view class="value" :class="{'positive': result.grossProfitRate > 0, 'negative': result.grossProfitRate < 0}">
            {{ showResult ? result.grossProfitRate + '%' : '--' }}
          </view>
        </view>
        <view class="row">
          <view class="label">纯利润率</view>
          <view class="value" :class="{'positive': result.netProfitRate > 0, 'negative': result.netProfitRate < 0}">
            {{ showResult ? result.netProfitRate + '%' : '--' }}
          </view>
        </view>
        <view class="row">
          <view class="label">预估ROI</view>
          <view class="value" :class="{'positive': result.estimatedROI > 1, 'negative': result.estimatedROI < 1}">
            {{ showResult ? result.estimatedROI : '--' }}
          </view>
        </view>
        <view class="row">
          <view class="label">保本ROI</view>
          <view class="value">
            {{ showResult ? result.breakEvenROI : '--' }}
          </view>
        </view>
        <view v-if="!showResult" class="placeholder">
          <text class="placeholder-text">点击上方按钮开始计算</text>
        </view>
      </view>
      <button class="addShortcut" open-type="addShortcut" :bindaddshortcut="eventHandler">添加到桌面</button>
      <button class="share" open-type="share">分享</button>
    </view>
  </view>
</template>

<script>
import {
  showAdConfirmModal,
  adVideoCreate,
  adVideoShow,
  adBannerIdDouyin,
  adBannerIdKuaishou,
} from "@/common/ad";
export default {
  data() {
    return {
      banner: null,
      adBannerIdDouyin: adBannerIdDouyin,
      adBannerIdKuaishou: adBannerIdKuaishou,
      showResult: false,
      isUnlock: false,
      formData: {
        cost: '',           // 成本
        price: '',          // 售价
        returnRate: '',     // 退货率
        serviceFeeRate: '', // 平台服务费率
      },
      result: {
        estimatedProfit: 0,    // 预估利润
        settlementProfit: 0,   // 结算利润
        grossProfitRate: 0,    // 毛利润率
        netProfitRate: 0,      // 纯利润率
        estimatedROI: 0,       // 预估ROI
        breakEvenROI: 0,       // 保本ROI
      },
    };
  },
  onLoad() {
    adVideoCreate();
  },
  methods: {
    // 验证成本输入
    validateCost(e) {
      let value = e.detail.value;
      if (value < 0) {
        this.formData.cost = '0';
        this.global.toast('成本不能为负数');
      }
    },
    // 格式化成本
    formatCost() {
      if (this.formData.cost) {
        this.formData.cost = parseFloat(this.formData.cost).toFixed(2);
      }
    },
    // 验证售价输入
    validatePrice(e) {
      let value = e.detail.value;
      if (value < 0) {
        this.formData.price = '0';
        this.global.toast('售价不能为负数');
      }
    },
    eventHandler(e) {
      if (e.detail.errNo) {
        this.global.toast("添加到桌面失败");
      } else {
        this.global.toast("添加到桌面成功");
      }
    },
    // 格式化售价
    formatPrice() {
      if (this.formData.price) {
        this.formData.price = parseFloat(this.formData.price).toFixed(2);
      }
    },
    // 验证退货率输入
    validateReturnRate(e) {
      let value = e.detail.value;
      if (value < 0) {
        this.formData.returnRate = '0';
        this.global.toast('退货率不能为负数');
      } else if (value > 100) {
        this.formData.returnRate = '100';
        this.global.toast('退货率不能超过100%');
      }
    },
    // 格式化退货率
    formatReturnRate() {
      if (this.formData.returnRate) {
        this.formData.returnRate = parseFloat(this.formData.returnRate).toFixed(2);
      }
    },
    // 验证服务费率输入
    validateServiceFeeRate(e) {
      let value = e.detail.value;
      if (value < 0) {
        this.formData.serviceFeeRate = '0';
        this.global.toast('服务费率不能为负数');
      } else if (value > 100) {
        this.formData.serviceFeeRate = '100';
        this.global.toast('服务费率不能超过100%');
      }
    },
    // 格式化服务费率
    formatServiceFeeRate() {
      if (this.formData.serviceFeeRate) {
        this.formData.serviceFeeRate = parseFloat(this.formData.serviceFeeRate).toFixed(2);
      }
    },
    // 验证表单
    validateForm() {
      if (!this.formData.cost) {
        this.global.toast('请输入成本');
        return false;
      }
      if (!this.formData.price) {
        this.global.toast('请输入售价');
        return false;
      }
      if (!this.formData.returnRate) {
        this.global.toast('请输入退货率');
        return false;
      }
      if (!this.formData.serviceFeeRate) {
        this.global.toast('请输入平台服务费率');
        return false;
      }
      return true;
    },
    calculateRoi(price, cost, returnRate, serviceFeeRate) {
      // 计算预估利润（不考虑退货）
      const estimatedProfit = price - cost;
      
      // 计算结算利润（考虑退货和服务费）
      const settlementProfit = estimatedProfit * (1 - returnRate/100) * (1 - serviceFeeRate/100);
      
      // 计算毛利润率
      const grossProfitRate = (estimatedProfit / price) * 100;
      
      // 计算纯利润率
      const netProfitRate = (settlementProfit / price) * 100;
      
      // 计算预估ROI
      const estimatedROI = (estimatedProfit / cost).toFixed(2);
      
      // 计算保本ROI（考虑退货和服务费）
      const breakEvenROI = (1 / ((1 - returnRate/100) * (1 - serviceFeeRate/100))).toFixed(2);
      
      this.result.estimatedProfit = estimatedProfit.toFixed(2);
      this.result.settlementProfit = settlementProfit.toFixed(2);
      this.result.grossProfitRate = grossProfitRate.toFixed(2);
      this.result.netProfitRate = netProfitRate.toFixed(2);
      this.result.estimatedROI = estimatedROI;
      this.result.breakEvenROI = breakEvenROI;
      this.showResult = true;
    },
    getResult() {
      this.calculateRoi(
        parseFloat(this.formData.price),
        parseFloat(this.formData.cost),
        parseFloat(this.formData.returnRate),
        parseFloat(this.formData.serviceFeeRate)
      );
      this.isUnlock = true;
    },
    submit() {
      if (!this.validateForm()) {
        return;
      }
      if (!this.isUnlock) {
        showAdConfirmModal(() => {
          try {
            adVideoShow(() => {
              this.getResult();
            });
          } catch (error) {
            this.getResult();
          }
        });
      } else {
        this.getResult();
      }
    },
  },
};
</script>

<style scoped lang="scss">
.index {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
  padding: 30rpx;
  
  .center {
    max-width: 800rpx;
    margin: 0 auto;
  }
}

.header {
  text-align: center;
  margin-bottom: 20rpx;
  padding: 0;
  
  .title {
    font-size: 48rpx;
    font-weight: 600;
    color: #333;
    display: block;
    margin-bottom: 16rpx;
  }
  
  .subtitle {
    font-size: 28rpx;
    color: #666;
  }
}

.section-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #222;
  padding: 36rpx 30rpx 24rpx 30rpx;
  border-bottom: 2rpx solid rgba(0, 0, 0, 0.05);
  background: rgba(0, 0, 0, 0.02);
  letter-spacing: 2rpx;
}

.btn-text {
  display: inline-block;
  position: relative;
}

.ind_from {
  background: #fafbfc;
  margin-top: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
  backdrop-filter: blur(10px);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  
  .row {
    padding: 30rpx;
    display: flex;
    align-items: center;
    border-bottom: 2rpx solid rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    
    &:hover {
      background: rgba(0, 0, 0, 0.02);
    }
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      width: 240rpx;
      flex-shrink: 0;
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
    
    .value {
      flex: 1;
      
      .input {
        width: 100%;
        height: 80rpx;
        background: #f8f9fa;
        border: 2rpx solid #e9ecef;
        border-radius: 12rpx;
        padding: 0 24rpx;
        font-size: 28rpx;
        color: #333;
        transition: all 0.3s ease;
        
        &:focus {
          border-color: #4a90e2;
          box-shadow: 0 0 0 3rpx rgba(74, 144, 226, 0.1);
        }
      }
    }
  }
  
  &:hover {
    transform: translateY(-4rpx);
    box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.08);
  }
}

.btn {
  margin: 40rpx 0 0 0;
  background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%);
  color: #fff;
  text-align: center;
  padding: 24rpx 0;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 500;
  box-shadow: 0 8rpx 20rpx rgba(74, 144, 226, 0.2);
  transition: all 0.3s ease;
  
  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 10rpx rgba(74, 144, 226, 0.2);
  }
}

.result {
  .row {
    .label {
      color: #666;
    }
    
    .value {
      font-weight: 600;
      color: #4a90e2;
      
      &.positive {
        color: #2ecc71;
      }
      
      &.negative {
        color: #e74c3c;
      }
    }
  }
}

.pub_ad_banner {
  margin-top: 40rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.05);
}

// 添加动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.ind_from {
  animation: fadeIn 0.5s ease-out;
}

// 添加响应式设计
@media screen and (min-width: 768px) {
  .index {
    padding: 60rpx;
  }
  
  .ind_from {
    .row {
      padding: 40rpx;
      
      .label {
        font-size: 32rpx;
      }
      
      .value {
        .input {
          height: 90rpx;
          font-size: 32rpx;
        }
      }
    }
  }
  
  .btn {
    padding: 30rpx 0;
    font-size: 36rpx;
  }
}

.placeholder {
  text-align: center;
  padding: 40rpx 0;
  
  .placeholder-text {
    font-size: 28rpx;
    color: #999;
    position: relative;
    padding: 0 30rpx;
    
    &::before,
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      width: 60rpx;
      height: 2rpx;
      background: #ddd;
    }
    
    &::before {
      left: -80rpx;
    }
    
    &::after {
      right: -80rpx;
    }
  }
}

.result {
  .row {
    .value {
      opacity: 1;
      transition: opacity 0.3s ease;
      
      &:not(:empty) {
        opacity: 1;
      }
    }
  }
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 32rpx 32rpx;
  padding: 32rpx 24rpx 24rpx 24rpx;

  .form-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 10rpx;
    background: none;
    box-shadow: none;
    padding: 0;
  }

  .label {
    width: 200rpx;
    font-size: 26rpx;
    color: #888;
    text-align: right;
    margin-bottom: 0;
    font-weight: 400;
    padding-right: 8rpx;
  }

  .input-unit-group {
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(51,138,255,0.04);
    border: 2rpx solid #e9ecef;
    transition: border-color 0.3s;
    overflow: hidden;

    &:focus-within {
      border-color: #338aff;
      .unit.blue {
        background: #2266cc;
      }
    }

    .input {
      flex: 1;
      height: 64rpx;
      border: none;
      border-radius: 0;
      padding: 0 24rpx;
      font-size: 30rpx;
      color: #333;
      background: transparent;
      outline: none;
      box-shadow: none;
    }

    .unit {
      min-width: 70rpx;
      height: 64rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      border: none;
      border-radius: 0 16rpx 16rpx 0;
      background: #f5f7fa;
      color: #338aff;
      font-weight: 500;
      transition: background 0.3s, color 0.3s;
    }
    .unit.blue {
      background: #338aff;
      color: #fff;
    }
  }
}

// 响应式
@media screen and (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
    gap: 24rpx;
    padding: 24rpx 8rpx 8rpx 8rpx;
  }
  .section-title {
    font-size: 30rpx;
    padding: 24rpx 16rpx 16rpx 16rpx;
  }
}
</style>